package com.lee.enjoy221113_retrofit;

import org.jetbrains.annotations.NotNull;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import okhttp3.Call;
import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;

/**
 * @ProjectName: LifeCycleTest
 * @Package: com.lee.enjoy221113_retrofit
 * @ClassName: EnjoyRetrofit
 * @Description: java类作用描述
 * @Author: 李占伟
 * @CreateDate: 2022/11/14 15:09
 * @UpdateUser: 更新者
 * @UpdateDate: 2022/11/14 15:09
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */

public class EnjoyRetrofit {


    public final Call.Factory callFactory;
    private final Map<Method,ServiceMethod> serviceMethodCache = new ConcurrentHashMap<>();
    public final HttpUrl baseUrl;

    public EnjoyRetrofit(Call.Factory callFactory, HttpUrl httpUrl) {
        this.callFactory = callFactory;
        this.baseUrl = httpUrl;
    }

    private ServiceMethod loadServiceMethod(Method method){
        ServiceMethod serviceMethod = serviceMethodCache.get(method);
        if (serviceMethod!=null){
            return serviceMethod;
        }
        synchronized (serviceMethodCache){
            serviceMethod = serviceMethodCache.get(method);
            if (serviceMethod==null){
                synchronized (serviceMethodCache){
                    serviceMethod = new ServiceMethod.Builder(this,method).build();
                    serviceMethodCache.put(method,serviceMethod);
                }
            }
        }
        return serviceMethod;
    }

    @NotNull
    public <T> T create(@NotNull Class<T> service) {
        //动态代理
        return (T)Proxy.newProxyInstance(service.getClassLoader(), new Class[]{service},
                new InvocationHandler() {
                    @Override
                    public Object invoke(Object o, Method method, Object[] args) throws Throwable {
                        ServiceMethod serviceMethod = loadServiceMethod(method);
                        return serviceMethod.invoke(args);
                    }
                });
    }

    static final class Builder{
        private HttpUrl httpUrl;
        private HttpUrl baseUrl;
        private Call.Factory callFactory;//okhttpclient 实现类 唯一
        public Builder callFactory(Call.Factory factory){//定制你自己的okhttpclient
            this.callFactory = factory;
            return this;
        }
        public Builder baseUrl(String baseUrl){
            this.baseUrl = HttpUrl.parse(baseUrl);
            return this;
        }

        public EnjoyRetrofit build(){
            if (baseUrl== null){
                throw new RuntimeException("BaseUrl must be required!");
            }

            if (callFactory == null){
                //创建默认的
                callFactory = new OkHttpClient();
            }
            return new EnjoyRetrofit(callFactory,baseUrl);
        }

    }
}
